using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Collections.Specialized;
using System.Globalization;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Configuration;

namespace Blazing.Web.Modules
{
    /// <summary>
    /// Matches urls agains a regex string and rewrites them
    /// </summary>
    public class PostRequestModule : System.Web.IHttpModule
    {
        public PostRequestModule()
        {

        }

        #region IHttpModule Members

        public void Dispose()
        {

        }

        public void Init(HttpApplication context)
        {
            context.AuthenticateRequest += context_AuthenticateRequest;
        }

        void context_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            Rewrite(app.Request.Path, app);
        }

        protected void Rewrite(string requestedPath,
         HttpApplication app)
        {
            string path = app.Request.Url.PathAndQuery;

            PostRequestConfig rules = WebConfigurationManager.GetSection("RewriterConfig") as PostRequestConfig;
            
            foreach (UrlRule ri in rules.UrlRules)
            {
                string rule = ri.Url;
                string sendto = ri.Rewrite;
                Regex ex = new Regex(rule, RegexOptions.IgnoreCase);
                if (ex.IsMatch(path))
                {
                    string newpath = ex.Replace(path, sendto);
                    string query = newpath.LastIndexOf("?") > -1 ? newpath.Substring(newpath.LastIndexOf("?") + 1) : "";
                    newpath = newpath.LastIndexOf("?") > -1 ? newpath.Remove(newpath.LastIndexOf("?")) : newpath;

                    if (ri.RewriteType == RewriteTypes.Rewrite)
                    {
                        if (ri.AppendHostAsQueryParam)
                            query = query + (query.Length > 1 ? "&" : "") + "host=" + app.Context.Request.Url.Host;
                        app.Context.RewritePath(newpath, app.Context.Request.PathInfo, query); 
                    }
                    else
                    {
                        app.Context.Response.Redirect(string.Format("{0}{1}{2}", newpath, !string.IsNullOrEmpty(query) ? "?" : "", query), false);

                        //Response.Redirect changes the status code, check and set to what is 
                        //defined in the config
                        if (app.Context.Response.StatusCode != ri.StatusCode)
                        {
                            app.Context.Response.StatusCode = ri.StatusCode;
                        }

                        app.Context.Response.End();
                    }

                    break;
                }
            }
        }
    }
    #endregion
}
